#!/usr/bin/python3
from openpyxl import load_workbook
import datetime
import os, gc
from .Base_Plugin import Base_Plugin
from utils import My_Util
from enum import Enum, auto


def get_table_real_name(table_name, tenant):
    """
    获取表的真实名称
    """
    if tenant:
        prefix = f"""{tenant["table_prefix"]}{tenant["delimiter"]}"""
        suffix = f"""{tenant["delimiter"]}{tenant["tenant_id"]}"""
        if prefix in table_name and suffix in table_name:
            table_name = table_name.replace(prefix, "").replace(suffix, "")
    return table_name


def get_table_tenant_name(table_name, tenant):
    """
    获取带租户的表名称
    """
    table_name = "{}{}{}{}{}".format(
        tenant["table_prefix"],
        tenant["delimiter"],
        get_table_real_name(table_name.lower(), tenant),
        tenant["delimiter"],
        tenant["tenant_id"],
    )
    return table_name


class Table:
    """
    表
    """

    def __init__(self, name: str, rows: int, tenant=None) -> None:
        self.name = name
        self.rows = rows
        self.tenant = tenant


class Analysis_Null_Table(Base_Plugin):
    """分析空数据表插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.database = self.context["db"]["database"]
        self.tenant = self.context["init_tenant"]
        self.table_prefix = self.tenant["table_prefix"]
        self.delimiter = self.tenant["delimiter"]
        self.tenant_id = self.tenant["tenant_id"]

    def depend_on_db(self) -> bool:
        """
        依赖数据库
        """
        return True

    def get_tables_from_database(self, tenant=None):
        """
        从数据库中获取所有表
        """
        conn = self.get_datasource()
        with conn.cursor() as cursor:
            cursor.execute(
                f"""SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = '{self.database}' AND TABLE_NAME LIKE '{get_table_tenant_name('%', tenant)}' ORDER BY table_rows DESC;"""
            )
            result = cursor.fetchall()
        tables_info = list[Table]()
        for row in result:
            table_info = Table(row[0], row[1], tenant)
            tables_info.append(table_info)
        return tables_info

    def get_log_data_count(self, tables: list[Table]) -> str:
        """
        获取统计日志
        """
        null_table_list = list(filter(lambda item: item.rows == 0, tables))
        return "\n".join(
            list(
                map(
                    lambda item: f"""表名：{item.name} -> 数据量：{item.rows}""",
                    null_table_list,
                )
            )
        )

    def save_file(self, sql, dir):
        with open(dir, "w", encoding="utf-8") as f:
            f.write(sql)

    def run(self, workspace, source):
        _target_path = os.path.join(workspace, "analysis", "null_table")
        if not os.path.exists(_target_path):
            os.makedirs(_target_path)

        # 获取数据库中的表结构
        database_tables = self.get_tables_from_database(self.tenant)
        log_content = self.get_log_data_count(database_tables)

        log_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        self.save_file(
            log_content,
            os.path.join(
                _target_path,
                "{}.sql".format(log_name),
            ),
        )

        gc.collect()
        return source
